﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using PBMessage;
public class UIReadyRoom :BaseWidget
{
    GameObject UserItemPrefab;
    GameObject HeroItemPrefab;
    ReadyRoomModel roomModel;

    public GameObject UserGrid;
    public GameObject HeroGrid;
    public GameObject ReadyBtn;
    public GameObject ReadyOKInfo;

    string SelectHeroID = "";
    bool IsReady = false;
    public override void OnLoad()
    {
        UserItemPrefab = Game.UI.GetPrefab("ReadyRoomUserItem");
        HeroItemPrefab = Game.UI.GetPrefab("ReadyRoomHeroItem");
        roomModel = Game.Model.Get<ReadyRoomModel>();
        UIEventListener.Get(ReadyBtn).onClick = OnClickReadyOKButton;
        ShowUserList();
        ShowHeroList();
    }

    void ShowUserList()
    {
        for (int i = 0; i < roomModel.PlayerList.Count;i++)
        {
           GameObject Item = Game.UI.AddChild(UserGrid,UserItemPrefab);
           Item.transform.Find("Label").GetComponent<UILabel>().text = roomModel.PlayerList[i].UserName.ToString();
        }
        UserGrid.GetComponent<UIGrid>().Reposition();
    }

    void ShowHeroList()
    {
        foreach(KeyValuePair<string,XmlUnit> unit in UnitManager.Instance.xmlUnits)
        {
            if (unit.Value.UnitType == "Unit")
            {
                GameObject Item = Game.UI.AddChild(HeroGrid, HeroItemPrefab);
                Item.name = unit.Value.Name;
                Item.transform.Find("NameLabel").GetComponent<UILabel>().text = unit.Value.ShowName;
                UIEventListener.Get(Item).onClick = OnSelectHero;
            }
        }
    }


    public void OnSelectHero(GameObject go)
    {
        if (IsReady == false)
        {
            SelectHero(go.name);
        }
    }

    void SelectHero(string selId)
    {
        if (SelectHeroID != "")
        {
            HeroGrid.transform.Find(SelectHeroID.ToString()).Find("Select").gameObject.SetActive(false);
        }
        SelectHeroID = selId;
        HeroGrid.transform.Find(SelectHeroID.ToString()).Find("Select").gameObject.SetActive(true);
    }

    public void OnClickReadyOKButton(GameObject go)
    {
        IsReady = true;
        if (SelectHeroID == "") 
        {
            SelectHero(UnitManager.Instance.xmlUnits.GetEnumerator().Current.Value.Name);
        }
        ReadyBtn.SetActive(false);
        ReadyOKInfo.SetActive(true);
        Game.Packet.SendSynReadyPlayerState(true,SelectHeroID);
    }



    public override void OnExit()
    {
        Game.Model.Destory<ReadyRoomModel>();
    }
}
